//
//  AccountController.swift
//  首页账号界面
//
//  Created by smile on 2019/6/10.
//  Copyright © 2019 ixuea. All rights reserved.
//

import UIKit

//导入发布订阅框架
import SwiftEventBus

//主题框架
import SwiftTheme

//日志框架
import CocoaLumberjack

class AccountController: BaseTitleController {
    
    //日志Tag
    private static let TAG="AccountController"
    
    /// 用户信息容器
    @IBOutlet weak var svUserInfo: UIStackView!
    
    /// 头像
    @IBOutlet weak var ivAvatar: UIImageView!
    
    /// 昵称
    @IBOutlet weak var lbNickname: UILabel!
    
    /// 描述
    @IBOutlet weak var lbDescription: UILabel!
    
    /// 签到
    @IBOutlet weak var btSign: UIButton!
    
    /// 动态数
    @IBOutlet weak var lbFeedCount: UILabel!
    
    /// 好友数
    @IBOutlet weak var lbFriendCount: UILabel!
    
    /// 粉丝数
    @IBOutlet weak var lbFansCount: UILabel!
    
    /// 编辑用户信息
    @IBOutlet weak var btEditProfile: UIButton!
    
    /// 好友容器
    @IBOutlet weak var svFriend: UIStackView!
    
    /// 粉丝容器
    @IBOutlet weak var svFans: UIStackView!
    
    /// 我的二维码容器
    @IBOutlet weak var svCode: UIStackView!
    
    /// 我的消息容器
    @IBOutlet weak var svMessage: UIStackView!
    
    
    /// 我的消息
    @IBOutlet weak var lbMessage: UILabel!
    
    /// 商城容器
    @IBOutlet weak var svShop: UIStackView!
    
    /// 我的订单容器
    @IBOutlet weak var svOrder: UIStackView!
    
    /// 我的订单（接口签名和加密）容器
    @IBOutlet weak var svNewOrder: UIStackView!
    
    /// 设置容器
    @IBOutlet weak var svSettings: UIStackView!
    
    /// 夜间模式
    @IBOutlet weak var stNight: UISwitch!
    
    /// 夜间模式容器
    @IBOutlet weak var svNight: UIStackView!
    
    /// 定时关闭容器
    @IBOutlet weak var svTimeClose: UIStackView!
    
    /// 关于爱学啊（可视化布局）
    @IBOutlet weak var svAbout: UIStackView!
    
    /// 关于爱学啊（代码自动布局）
    @IBOutlet weak var svAboutCode: UIStackView!
    
    /// 关于爱学啊（其他Storyboard）
    @IBOutlet weak var svAboutOther: UIStackView!
    
    /// 红点
    var hub:RKNotificationHub!
    
    override func initViews() {
        super.initViews()
        DDLogWarn("AccountController initViews",tag:AccountController.TAG)
        
        setTitle("账号")
        
        //头像圆角
        ViewUtil.showRadius(ivAvatar, 30)
        
        //签到按钮边框
        btSign.showColorPrimaryBorder()
        
        //签到按钮圆角
        ViewUtil.showRadius(btSign, 15)
        
        //测试昵称夜间模式
        lbNickname.theme_textColor=["#000", "#F00"]
        
        //从偏好设置中恢复状态
        stNight.setOn(PreferenceUtil.isNight(), animated: true)
        
        //创建红点
        hub=RKNotificationHub(view: lbMessage)
        
        //设置他的绝对位置
//        hub.setCircleAtFrame(CGRect(x: 2, y: 2, width: 30, height: 30)
        
        //设置相对偏移位置
//        hub.moveCircleBy(x: 10, y: 2)
        
        //设置大小
        //设置原来大小的多少倍
        hub.scaleCircleSize(by: 0.8)
    }
    
    override func initDatas() {
        super.initDatas()
        DDLogWarn("AccountController initDatas",tag:AccountController.TAG)
        
        fetchData()
    }
    
    func fetchData() {
        Api.shared.userDetail(id: PreferenceUtil.userId()!).subscribeOnSuccess { (data) in
            if let data=data?.data {
                self.showData(data)
            }
        }.disposed(by: disposeBag)
    }
    
    func showData(_ data:User) {
        //显示头像
        ImageUtil.showAvatar(ivAvatar, data.avatar)
        
        //显示昵称
        lbNickname.text=data.nickname
        
        //显示描述
        lbDescription.text=data.formatDescription
        
        //好友数
        lbFriendCount.text="\(data.followings_count)"
        
        //粉丝数
        lbFansCount.text="\(data.followers_count)"
        
        updateMessageUnreadCount()
    }
    
    override func initListeners() {
        super.initListeners()
        
        //用户信息点击
        svUserInfo.addGestureRecognizer(UITapGestureRecognizer(target: self, action: #selector(onUserInfoClick)))
        
        //好友列表点击
        svFriend.addGestureRecognizer(UITapGestureRecognizer(target: self, action: #selector(onFriendClick)))
        
        //粉丝列表点击
        svFans.addGestureRecognizer(UITapGestureRecognizer(target: self, action: #selector(onFansClick)))
        
        //我的二维码点击
        svCode.addGestureRecognizer(UITapGestureRecognizer(target: self, action: #selector(onCodeClick)))
        
        //我的消息点击
        svMessage.addGestureRecognizer(UITapGestureRecognizer(target: self, action: #selector(onMessageClick)))
        
        //商城点击
        svShop.addGestureRecognizer(UITapGestureRecognizer(target: self, action: #selector(onShopClick)))
        
        //订单点击
        svOrder.addGestureRecognizer(UITapGestureRecognizer(target: self, action: #selector(onOrderClick)))
        
        //新订单点击
        //主要颜色接口签名和加密
        svNewOrder.addGestureRecognizer(UITapGestureRecognizer(target: self, action: #selector(onNewOrderClick)))
        
        //设置点击
        svSettings.addGestureRecognizer(UITapGestureRecognizer(target: self, action: #selector(onSettingsClick)))
        
        //关于爱学啊（可视化布局）点击
            svAbout.addGestureRecognizer(UITapGestureRecognizer(target: self, action: #selector(onAboutClick)))
        
        //关于爱学啊（代码自动布局）点击
        svAboutCode.addGestureRecognizer(UITapGestureRecognizer(target: self, action: #selector(onAboutCodeClick)))
    
        //关于爱学啊（其他Storyboard）点击
        svAboutOther.addGestureRecognizer(UITapGestureRecognizer(target: self, action: #selector(onAboutOtherClick)))
        
        //监听用户资料改变了
        SwiftEventBus.onMainThread(self, name: ON_USER_INFO_CHANGED) { (sender) in
            //重新获取用户信息
            self.fetchData()
        }
        
        //监听消息未读数改变了
        SwiftEventBus.onMainThread(self, name: ON_MESSAGE_COUNT_CHANGED) { (sender) in
            self.updateMessageUnreadCount()
        }

    }
    
    /// 更新消息未读数
    func updateMessageUnreadCount() {
        hub.count=Int32(MessageUtil.getUnreadMessageCount())
        hub.pop()
    }
    
    /// 扫描二维码点击
    ///
    /// - Parameter sender: <#sender description#>
    @IBAction func onScanClick(_ sender: Any) {
        print("AccountController onScanClick")
        
        ScanController.start(navigationController!)
    }
    
    /// 用户信息点击
    @objc func onUserInfoClick() {
        print("AccountController onUserInfoClick")
        
        UserDetailController.start(navigationController!, userId: PreferenceUtil.userId()!)
    }
    
    /// 好友列表点击
    @objc func onFriendClick() {
        print("AccountController onFriendClick")
        
        UserController.start(navigationController!, PreferenceUtil.userId()!, .friend)
    }
    
    /// 粉丝列表点击
    @objc func onFansClick() {
        print("AccountController onFansClick")
        
        UserController.start(navigationController!, PreferenceUtil.userId()!, .fans)
    }
    
    /// 我的二维码点击
    @objc func onCodeClick() {
        print("AccountController onCodeClick")
        
        CodeController.start(navigationController!, PreferenceUtil.userId()!)
    }
    
    /// 我的消息点击
    @objc func onMessageClick() {
        print("AccountController onMessageClick")
        
        MessageController.start(navigationController!)
    }
    
    /// 商城点击
    @objc func onShopClick() {
        print("AccountController onShopClick")
        DDLogError("AccountController onShopClick")
        
        ShopController.start(navigationController!)
    }
    
    /// 订单点击
    @objc func onOrderClick() {
        print("AccountController onOrderClick")
        
        OrderController.start(navigationController!)
    }
    
    /// 新订单点击
    @objc func onNewOrderClick() {
        print("AccountController onNewOrderClick")
        
        NewOrderController.start(navigationController!)
    }
    
    /// 设置点击
    @objc func onSettingsClick() {
        print("AccountController onSettingsClick")
        
        SettingController.start(navigationController!)
    }
    
    /// 关于爱学啊（可视化布局）点击
    @objc func onAboutClick() {
        print("AccountController onAboutClick")
        
        AboutController.start(navigationController!)
    }
    
    /// 关于爱学啊（代码自动布局）点击
    @objc func onAboutCodeClick() {
        print("AccountController onAboutCodeClick")
        
        AboutCodeController.start(navigationController!)
    }
    
    /// 关于爱学啊（其他Storyboard）点击
    @objc func onAboutOtherClick() {
        print("AccountController onAboutOtherClick")
        
        AboutOtherController.start(navigationController!)
    }
    
    /// 编辑用户资料点击
    ///
    /// - Parameter sender: <#sender description#>
    @IBAction func onEditProfileClick(_ sender: Any) {
        print("AccountController onEditProfileClick")
        
        ProfileController.start(navigationController!)
    }
    
    /// 退出按钮点击事件
    ///
    /// - Parameter sender: <#sender description#>
    @IBAction func onLogoutClick(_ sender: Any) {
        //AppDelegate.shared.logout()
        
        //显示一个确认弹窗
        //因为我们本质是想留住用户
        let alertController=UIAlertController(title: "提示", message: "你确定退出吗？", preferredStyle: .alert)
        
        //确定回调
        let confirmAction=UIAlertAction(title: "确定", style: .default) { (action) in
            AppDelegate.shared.logout()
        }
        
        //取消回调
        let cancelAction=UIAlertAction(title: "取消", style: .default, handler: nil)
        
        //将动作添加到控制器
        alertController.addAction(confirmAction)
        alertController.addAction(cancelAction)
        
        //显示
        present(alertController, animated: true, completion: nil)
    }
    
    
    /// 夜间模式切换
    ///
    /// - Parameter sender: <#sender description#>
    @IBAction func onNightChanged(_ sender: UISwitch) {
//        ThemeManager.setTheme(index: sender.isOn ? 1:0)
        
        //调用AppDelegate中设置夜间模式的方法
        AppDelegate.shared.setNight(sender.isOn)
        
        //将值保存到偏好设置
        PreferenceUtil.setNight(sender.isOn)
    }

    override func pageId() -> String? {
        return "Account"
    }
}
